package com.link.play.fit.ai.ui.main.foodDatabase

import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import com.google.gson.Gson
import com.link.play.fit.ai.R
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.base.goToAc
import com.link.play.fit.ai.base.goToAcForResult
import com.link.play.fit.ai.bean.CalendarStatusData
import com.link.play.fit.ai.bean.CollectFoodInfoData
import com.link.play.fit.ai.bean.toRecentlyEatenData
import com.link.play.fit.ai.databinding.AcLogFoodBinding
import com.link.play.fit.ai.databinding.LayoutPowerPlateBinding
import com.link.play.fit.ai.store.CloudStore
import com.link.play.fit.ai.store.CloudStore.DOC_CALENDAR_STATUS_LIST_DATA_KEY
import com.link.play.fit.ai.store.CloudStore.DOC_SAVE_FOOD_COLLECT_DATA
import com.link.play.fit.ai.store.CloudStore.deleteList
import com.link.play.fit.ai.ui.dialog.ChangeServingDialog
import com.link.play.fit.ai.ui.main.GlobalViewModel
import com.link.play.fit.ai.ui.main.MainAc
import com.link.play.fit.ai.ui.main.saveFood.details.FoodDtailsAc
import com.link.play.fit.ai.ui.main.saveFood.details.ModifyFoodNameAc
import com.link.play.fit.ai.ui.main.saveFood.details.modifyPage.ModifyCaloriesAc
import com.link.play.fit.ai.ui.main.saveFood.details.modifyPage.ModifyCarbsAc
import com.link.play.fit.ai.ui.main.saveFood.details.modifyPage.ModifyFatsAc
import com.link.play.fit.ai.ui.main.saveFood.details.modifyPage.ModifyProteinAc
import com.link.play.fit.ai.utils.DateEx
import com.link.play.fit.ai.utils.EventUtils
import kotlinx.coroutines.launch

//内购-添加食物-饮食
class LogFoodAc : BaseActivity<AcLogFoodBinding>(AcLogFoodBinding::inflate) {

    //首页的数据
    private var calendarStatusDataList: MutableList<CalendarStatusData> = mutableListOf()

    //收藏的食物 bean
    lateinit var collectBean: CollectFoodInfoData

    // 是不是编辑
    var Flag: Boolean = false
    private val powerPlate: LayoutPowerPlateBinding by lazy {
        LayoutPowerPlateBinding.bind(binding.powerPlate.root)
    }
    private val baseViewModel: GlobalViewModel by lazy {
        GlobalViewModel.getInstance(application)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initParams()
        initView()
        initData()
    }

    fun initParams() {
        try {
            //编辑和查看
            collectBean = intent.getSerializableExtra("bean") as CollectFoodInfoData
            Flag = true
        } catch (e: Exception) {
            //如果是新建的食物,添加时间戳
            collectBean = CollectFoodInfoData()
            collectBean.timeMillisecond = System.currentTimeMillis().toString()
            Flag = false
        }
    }

    fun initView() {
        binding.ivReturn.setOnClickListener {
            finish()
        }
        binding.ivShare.setOnClickListener {
            goToAc(FoodDtailsAc::class.java) {
                putExtra("bean", calendarStatusDataList.last())
                putExtra("foodBean", collectBean)
            }
        }
        binding.ivMore.setOnClickListener {
            binding.deleteFoodText.isVisible = !binding.deleteFoodText.isVisible
        }
        binding.deleteFoodText.setOnClickListener {
            deleteList(
                CloudStore.DOC_RECENTLY_LIST_DATA, DateEx.getyyMMdd(
                    collectBean.timeMillisecond.toLong()
                ), collectBean.timeMillisecond
            )
            baseViewModel.deleteRecentlyData(collectBean.toRecentlyEatenData())
            finish()
        }
        binding.ivSave.setOnClickListener {
            val f = !binding.ivSave.isSelected
            //收藏
            if (f) {
                checkData()
                if (binding.btnLog.isEnabled) {
                    collectBean.type = 3
                    CloudStore.addToList(
                        DOC_SAVE_FOOD_COLLECT_DATA,
                        date = DOC_SAVE_FOOD_COLLECT_DATA,
                        key = collectBean.timeMillisecond,
                        data = collectBean
                    )
                    binding.ivSave.isSelected = f
                }
            } else {
                deleteList(
                    DOC_SAVE_FOOD_COLLECT_DATA,
                    date = DOC_SAVE_FOOD_COLLECT_DATA,
                    key = collectBean.timeMillisecond,
                )
                binding.ivSave.isSelected = f
            }
        }
        binding.tvTime.text = DateEx.getHourAndMinute()
        binding.tvTapName.setOnClickListener {
            lifecycleScope.launch {
                val result = goToAcForResult(ModifyFoodNameAc::class.java) {
                    val str = resources.getString(R.string.tap_to_name)
                    if (binding.tvTapName.text == str) {
                        putExtra("name", "")
                    } else {
                        putExtra("name", binding.tvTapName.text.toString())
                    }
                }
                when (result.resultCode) {
                    RESULT_OK -> {
                        val data = result.data?.getStringExtra("result_key").toString()
                        if (TextUtils.isEmpty(data)) {
                            binding.tvTapName.text = resources.getString(R.string.tap_to_name)
                            collectBean.name = ""
                        } else {
                            binding.tvTapName.text = data
                            collectBean.name = data
                        }
                        checkData()
                    }
                }
            }
        }
        binding.tvNum.text = collectBean.servings.toInt().toString()
        binding.tvNum.setOnClickListener {
            ChangeServingDialog().apply {
                setData(collectBean.servings.toInt(), "")
                result = {
                    collectBean.servings = it.toDouble()
                    this@LogFoodAc.binding.tvNum.text = collectBean.servings.toInt().toString()
                    setServing()
                }
            }.show(supportFragmentManager, "changeNum")
        }
        binding.tvSubtractNum.setOnClickListener {
            collectBean.servings -= 1
            if (collectBean.servings < 1.0) collectBean.servings = 1.0
            binding.tvNum.text = collectBean.servings.toInt().toString()
            setServing()
        }
        binding.tvAddNum.setOnClickListener {
            collectBean.servings += 1
            binding.tvNum.text = collectBean.servings.toInt().toString()
            setServing()
        }
        binding.powerPlate.rlCalories.setOnClickListener {
            if (calendarStatusDataList.isEmpty()) return@setOnClickListener
            lifecycleScope.launch {
                val result = goToAcForResult(ModifyCaloriesAc::class.java) {
                    putExtra("value", collectBean.calories.toInt().toString())
                    putExtra("bean", calendarStatusDataList.last())
                }
                when (result.resultCode) {
                    RESULT_OK -> {
                        val cal = strToInt(result.data?.getStringExtra("result_key"))
                        powerPlate.tvCaloriesiNum.text = cal.toString()
                        collectBean.calories = cal.toDouble()
                        checkData()
                    }
                }
            }
        }
        binding.powerPlate.rlProtein.setOnClickListener {
            if (calendarStatusDataList.isEmpty()) return@setOnClickListener
            lifecycleScope.launch {
                val result = goToAcForResult(ModifyProteinAc::class.java) {
                    putExtra("value", collectBean.protein.toInt().toString())
                    putExtra("bean", calendarStatusDataList.last())
                }
                when (result.resultCode) {
                    RESULT_OK -> {
                        val value = strToInt(result.data?.getStringExtra("result_key").toString())
                        powerPlate.tvProteinNum.text = "${value}g"
                        collectBean.protein = value.toDouble()
                        checkData()
                    }
                }
            }
        }
        binding.powerPlate.rlCarbs.setOnClickListener {
            if (calendarStatusDataList.isEmpty()) return@setOnClickListener
            lifecycleScope.launch {
                val result = goToAcForResult(ModifyCarbsAc::class.java) {
                    putExtra("value", collectBean.carbs.toInt().toString())
                    putExtra("bean", calendarStatusDataList.last())
                }
                when (result.resultCode) {
                    RESULT_OK -> {
                        val value = strToInt(result.data?.getStringExtra("result_key").toString())
                        powerPlate.tvCarbsNum.text = "${value}g"
                        collectBean.carbs = value.toDouble()
                        checkData()
                    }
                }
            }
        }
        binding.powerPlate.rlFats.setOnClickListener {
            if (calendarStatusDataList.isEmpty()) return@setOnClickListener
            lifecycleScope.launch {
                val result = goToAcForResult(ModifyFatsAc::class.java) {
                    putExtra("value", collectBean.fats.toInt().toString())
                    putExtra("bean", calendarStatusDataList.last())
                }
                when (result.resultCode) {
                    RESULT_OK -> {
                        val value = strToInt(result.data?.getStringExtra("result_key").toString())
                        powerPlate.tvFatsNum.text = "${value}g"
                        collectBean.fats = value.toDouble()
                        checkData()
                    }
                }
            }
        }
        binding.btnLog.setOnClickListener {
            //添加到首页
            val red = collectBean.toRecentlyEatenData().apply {
                type = 3//自定义食物
            }
            CloudStore.addToList(
                CloudStore.DOC_RECENTLY_LIST_DATA,
                DateEx.getDayOfMonth(),
                collectBean.timeMillisecond,
                red
            )

            if (Flag) {
                //编辑的需要返回数据
                setResult(RESULT_OK, Intent().apply {
                    putExtra("recentlyEatenData", red)
                })
            } else {
                EventUtils.event("food_database_custom")
                //新建返回首页
                goToAc(MainAc::class.java) {
                    putExtra(
                        "logFood", Gson().toJson(
                            red.apply { createTime = collectBean.timeMillisecond })
                    )
                    addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                }
            }
            finish()
        }
    }

    fun initData() {
        lifecycleScope.launch {
            calendarStatusDataList = CloudStore.getList<CalendarStatusData>(
                CloudStore.DOC_CALENDAR_STATUS_LIST_DATA, DOC_CALENDAR_STATUS_LIST_DATA_KEY
            ) as MutableList<CalendarStatusData>
        }
        lifecycleScope.launch {
            val bean = CloudStore.getListItem<CollectFoodInfoData>(
                DOC_SAVE_FOOD_COLLECT_DATA,
                DOC_SAVE_FOOD_COLLECT_DATA,
                collectBean.timeMillisecond
            )
            if (bean != null) {
                binding.ivSave.isSelected = true
            }
        }
        if (!TextUtils.isEmpty(collectBean.name)) {
            binding.tvTapName.text = collectBean.name
        }
        binding.tvNum.text = collectBean.servings.toInt().toString()
        setServing()
        powerPlate.tvCaloriesiNum.text = collectBean.calories.toInt().toString()
        powerPlate.tvProteinNum.text = "${collectBean.protein.toInt()}g"
        powerPlate.tvCarbsNum.text = "${collectBean.carbs.toInt()}g"
        powerPlate.tvFatsNum.text = "${collectBean.fats.toInt()}g"
        checkData()
    }

    //设置名字边上的 X1
    fun setServing() {
        if (collectBean.servings == 1.0) {
            binding.tvServingAmount.visibility= View.GONE
        } else {
            binding.tvServingAmount.visibility= View.VISIBLE
            binding.tvServingAmount.text = "x${collectBean.servings.toInt()}"
        }
    }

    fun checkData() {
        var f = true
        if (TextUtils.isEmpty(collectBean.name)) {
            f = false
        }
        // 能量数值不能全为零
        if (collectBean.calories + collectBean.carbs + collectBean.protein + collectBean.fats == 0.0) {
            f = false
        }
        binding.btnLog.isEnabled = f
    }

    private fun strToInt(str: String?): Int {
        if (TextUtils.isEmpty(str)) return 0
        return str!!.toInt()
    }
}